<template>
  <div class="display-flex j-c-c a-i-c height100">
    <div class="login-form">
      <el-form ref="ruleForm" :model="form">
        <el-form-item prop="email" :rules="{required:true, message:'请输入账号', trigger:'change'}">
          <el-input placeholder="请输入账号" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item prop="pass" :rules="{required:true, message:'请输入密码', trigger:'change'}">
          <el-input type="password" placeholder="请输入密码" v-model="form.pass"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="width100" type="primary" @click="doLogin">登陆</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getUserInfo, handleLogin } from '@/api/Login'
import { isNull, clog } from '@/utils'

interface UserForm {
  name: string
  pass: string | number
}

export default {
  setup() {
    const store = useStore()
    const vueRouter = useRouter()

    const state = reactive({
      form: {
        name: 'admin',
        pass: '123qwe'
      } as UserForm,
      ruleForm: ref<any>(null)
    })

    const doLogin = async () => {
      clog('doLogin')
      handleLogin(state.form.name, state.form.pass).then(result => {
        store.dispatch('session/setToken', result.accessToken)

        getUserInfo(result.userId).then(res => {
          clog('getUserInfo', res)
          store.dispatch('session/setUser', res)
          vueRouter.push('/home')
        })
      })
    }

    return {
      ...toRefs(state),
      doLogin
    }
  }
}
</script>

<style lang="less" scoped>
.login-form {
  width: 300px;
  margin: 0 auto;
  padding: 30px;
  border-radius: 2px;
  box-shadow: 3px 3px 10px 8px #f1f1f1;
}
</style>
